#include "ac_sampler.h"
#include "adc_driver.h"

#include <stdio.h>

// 配置参数
static const ACSamplerConfig ac_config = {
    .sample_rate = 1000,        // 1000Hz采样率(1ms一次)
    .ac_frequency = 50,         // 50Hz交流电
    .voltage_ratio = 10000,     // 电压互感器100:1(×100存储)
    .current_ratio = 2000,      // 电流互感器20:1(×100存储)
    .bias_mv = 1650             // 1.65V偏置电压
};

// 采样结果缓存
static ACSampleResult g_sample_result;
static bool g_new_data_available = false;
//请求采样 标志
static bool g_request_sample = false;   
static uint32_t g_sample_timer = 0;
static uint32_t g_sample_count = 0;
// 1ms定时器中断服务程序
void ac_sampler(void) {

    // 读取ADC值(电压通道0，电流通道1)

    if(g_request_sample )
    {
            // 处理采样数据
            if(!ac_sampler_is_complete())
            {   
                uint16_t voltage_adc_mv =0;
                uint16_t current_adc_mv =0;
                adc_read(ADC_CHANNEL_5,NULL,&voltage_adc_mv);
                adc_read(ADC_CHANNEL_0,NULL,&current_adc_mv);
                ac_sampler_process_interrupt(voltage_adc_mv, current_adc_mv);
            }
    }

  

}

// 初始化系统
void ac_init() {
    adc_init();
    // 初始化采样器
    ac_sampler_init(&ac_config);
     g_request_sample=true;
}

void ac_process(void) 
{ 
       if (ac_sampler_is_complete()) 
       {
        // 获取结果
         ac_sampler_calculate();
        if (ac_sampler_get_result(&g_sample_result)) {
            g_new_data_available = true;
        }
        // 准备下一轮采样
        ac_sampler_reset();
        g_request_sample=false;
        g_sample_timer=0;
        g_sample_count++;

     }
     if(g_request_sample == false)
     {
        g_sample_timer++;
        if(g_sample_timer > 50)
        {
            g_request_sample = true;
        }
     }
}

uint16_t ac_get_current() 
{
    return g_sample_result.current_rms_ma*10;
}

uint16_t ac_get_voltage() 
{
    return g_sample_result.voltage_rms_mv/10;
}

//编写测试获取 电压电流值命令 msh shell 打印出来
void ac_show(int argc, char **argv)
{
    printf("current: %d mA\n", ac_get_current());
    printf("voltage: %d mV\n", ac_get_voltage());
    printf("g_sample_count: %ld \n", g_sample_count);

}



